// import { applyMiddleware, createStore } from "redux"; //! createStore 画横线 readux4.2以后 建议使用redux tookit
import languageReducer from "./language/languageReducer";
import recommendProductsReducer from "./recommendProducts/recommendProductsReducer";
// import thunk from "redux-thunk";
import { actionLog } from "./middleware/actionLog"; // 引入actionLog中间件,作为applyMiddleware的参数
import { productDetailSlice } from "./productDetail/slice"; // 引入产品详情的slice
import { combineReducers, configureStore } from "@reduxjs/toolkit"; //! 9.6 使用rudux-toolkit的combineReducers 不使用redux原生的

import { productSearchSlice } from "./productSearch/slice"; // 引入产品搜索的slice
import { userSlice } from "./user/slice"; // 引入用户登录的slice
import { shoppingCartSlice } from "./shoppingCart/slice";
import { orderSlice } from "./order/slice";

import { persistStore, persistReducer } from "redux-persist"; // 持久化redux
import storage from "redux-persist/lib/storage";

// ! persist配置
const persistConfig = {
  key: "root",
  storage, // 存储的地方 默认localstorage
  whitelist: ["user"], // 设置白名单
};

// 使用 combineReducers将reducers捆绑起来
// 用对象包裹起来

const rootReducer = combineReducers({
  language: languageReducer,
  recommendProducts: recommendProductsReducer,
  productDetail: productDetailSlice.reducer,
  productSearch: productSearchSlice.reducer,
  user: userSlice.reducer,
  shoppingCart: shoppingCartSlice.reducer,
  order: orderSlice.reducer,
});

// ! 加强版的reducer
const persistedReducer = persistReducer(persistConfig, rootReducer);

// ?替换原有单一的reducer
// const store = createStore(languageReducer);
// const store = createStore(rootReducer, applyMiddleware(thunk, actionLog)); // ? thunk 引入中间件thunk 可以返回一个函数，而不一定是js对象
// 在一个thunk action中可以完成一些列连续的action操作

const store = configureStore({
  // reducer: rootReducer,
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(actionLog), // 默认开启中间件 使用本身的api 就能返回中间件
  devTools: process.env.NODE_ENV !== "production", // 开启redux devTools浏览器插件
}); // ? 使用configureStore

// ! 加强版的store
const persistor = persistStore(store);

export type RootState = ReturnType<typeof store.getState>; //! ts语法 获取函数返回值类型。 typeof获取getSate返回的类型

export type AppDispatch = typeof store.dispatch; //! 获取store的dispatch类型 react-router v6的新特性

export default { store, persistor };
